package com.zhiwang.planet.util

import android.app.ActivityManager
import android.app.AppOpsManager
import android.app.usage.UsageStatsManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.provider.Settings
import android.util.Log
import com.zhiwang.planet.BuildConfig
import java.lang.Exception


object AppDetector {

    val TAG = "AppDetector"

    var usageStatsManager: UsageStatsManager? = null

    var activityManager: ActivityManager? = null

    var prevAppPkgName = ""

    private fun hasAppUsageStatsPermission(context: Context): Boolean {

        val appOps = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager?
        var mode = 0

        mode = appOps!!.checkOpNoThrow(
                AppOpsManager.OPSTR_GET_USAGE_STATS,
                android.os.Process.myUid(), context.packageName
        )

        return mode == AppOpsManager.MODE_ALLOWED
    }

    fun hasAppUsagePermission(activity: Context): Boolean =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                hasAppUsageStatsPermission(activity)
            } else true

    fun requestPermission(context: Context) {
        try {
            val intent = Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS)
            context.startActivity(intent)
        } catch (e: Exception) {

        }
    }

    fun queryAppUsage(context: Context, packageName: String): Boolean {


        val now = System.currentTimeMillis()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            if (usageStatsManager == null)
                usageStatsManager = context.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager

            val queryUsageStats =
                    usageStatsManager?.queryUsageStats(UsageStatsManager.INTERVAL_BEST, now - 1000 * 5, now)

            queryUsageStats?.sortBy { it.lastTimeUsed }

            val lastApp = if (queryUsageStats?.isEmpty() != false) null else queryUsageStats.last()

            if (BuildConfig.DEBUG)
                queryUsageStats?.forEach {
                    Log.i(TAG, "queryAppUsage: ${it.lastTimeUsed} ${it.packageName}")
                }

            lastApp?.apply {
                prevAppPkgName = this.packageName
            }
            //目标 app 使用一段时间后，没有应用的切换，查询到的 列表为空， lastApp  = null ；所以记录之前的包名
            return if (lastApp == null) prevAppPkgName == packageName else lastApp.packageName === packageName
        } else {
            if (activityManager == null)
                activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager

            val runningTasks = activityManager?.getRunningTasks(20)

            val first = runningTasks?.first()
            return first != null && first.topActivity.packageName.contains(packageName)
        }


    }

}